from django.contrib.auth import get_user_model
from backend.cews.models import StockItemGroup
from backend.cews.models import StockItem
from backend.users.models import GroupSetting
from logger.createlogger import create_logger
from django.contrib.auth.models import Group, Permission
from django.db import transaction
from backend.cews.models import StockItemTask, TaskGroup
from backend.eform.models import EformSchema

logger = create_logger(__name__)

User = get_user_model()


def bulk_update_or_create(data):
    creates= []
    updates= []
    
    user_dict = {
        user.username: user
        for user in User.objects.all()
    }

    group_dict = {
        g.name: g
        for g in Group.objects.all()
    }

    setting_dict = {
        s.id:s
        for s in GroupSetting.objects.all()
    } 
    
    with transaction.atomic():

        for d in data:
            print(d)
            old_setting = setting_dict.get(d['id'])
            group = group_dict.get(d['groupname'])
            user = user_dict.get(d['username'])
            if not group:
                raise ValueError(f"Group: {d['groupname']} has not been registered")
            
            if not user:
                raise ValueError(f"User: {d['username']} has not been registered") 
            
            if old_setting:
                update = False
                if  old_setting.expiry_date != d['expiry_date'] or \
                    old_setting.enable != d['enable']  :
                    update = True

                    if update:
                        # old_setting.users = user
                        # old_setting.group = group
                        old_setting.expiry_date = d['expiry_date']
                        old_setting.enable = d['enable']
                        old_setting.save()
                        print('update')
            else:
                if GroupSetting.objects.filter(users = user,group = group).exists():
                    raise ValueError('User and Group are unique')
                new_setting = GroupSetting(
                    users = user,
                    group = group,
                    expiry_date = d['expiry_date'],
                    enable = d['enable'],
                )
                user.groups.add(group)
                new_setting.save()
                print('save')

                    # logger.debug(f"{d}")

    
    # GroupSetting.objects.bulk_create(creates)
    # GroupSetting.objects.bulk_update(updates,['expiry_date','enable'])

    # logger.debug(f"{setting}")

    return True

def filter(groupname):
    return GroupSetting.objects.filter(group__name=groupname).order_by('-id')

        

def create_group_and_permission_and_task(group,can_do_task,can_do_sc, tasks, stockCodes):
    p_list = []

    with transaction.atomic():
        if can_do_task:
            p = Permission.objects.get(codename='can_do_maintenance_task')
            p_list.append(p)

        if can_do_sc:
            p = Permission.objects.get(codename='can_do_maintenance_by_stock_code')
            p_list.append(p)

        if group:
            new_group, created = Group.objects.get_or_create(name=group)
            if created:
                new_group.permissions.set(p_list)
            else:
                raise ValueError('Group is already existed')

            print(created)
            print(new_group)

        if tasks:
            for task in tasks:
                arr = task.split('. ')
                id = arr[0]
                eformSchema = EformSchema.objects.get(pk=id)
                tg = TaskGroup(
                    group=new_group,
                    eformSchema_id=eformSchema.id,
                    title=eformSchema.title,
                    formNo=eformSchema.formNo
                )
                tg.save()

        if stockCodes:
            for stock in stockCodes:
                arr = stock.split('. ')
                id = arr[0]
                s =StockItem.objects.get(pk=id)
                sig = StockItemGroup(
                    group=new_group,
                    stock_id=s.id,
                    stock_code=s.stock_code,
                    description=s.description
                )
                sig.save()

    return True


def patch_group_and_permission_and_task(group_id,can_do_task,can_do_sc, groupname, tasks, stockCodes):
    p_list = []
    p_remove_list = []

    with transaction.atomic():
        if can_do_task:
            tp = Permission.objects.get(codename='can_do_maintenance_task')
            p_list.append(tp)

        else:
            tp = Permission.objects.get(codename='can_do_maintenance_task')
            p_remove_list.append(tp)

        if can_do_sc:
            sp = Permission.objects.get(codename='can_do_maintenance_by_stock_code')
            p_list.append(sp)

        else:
            sp = Permission.objects.get(codename='can_do_maintenance_by_stock_code')
            p_remove_list.append(sp)
        
        group = Group.objects.get(pk=group_id)
        group.name = groupname
        group.save()

        for p in p_list:
            group.permissions.add(p)

        for pr in p_remove_list:
            group.permissions.remove(pr)

        if tasks:
            for task in tasks:
                arr = task.split('. ')
                id = arr[0]
                eformSchema = EformSchema.objects.get(pk=id)
                tg = TaskGroup(
                    group=group,
                    eformSchema_id=eformSchema.id,
                    title=eformSchema.title,
                    formNo=eformSchema.formNo
                )
                tg.save()

        if stockCodes:
            for stock in stockCodes:
                print(stock)
                arr = stock.split('. ')
                id = arr[0]
                s =StockItem.objects.get(pk=id)
                sig = StockItemGroup(
                    group=group,
                    stock_id=s.id,
                    stock_code=s.stock_code,
                    description=s.description
                )
                sig.save()

    return True
